package com.wl.dzt.sys.controller.fileupload;

import com.wl.dzt.basic.user.User;
import com.wl.dzt.oss.OSSFactory;
import com.wl.dzt.sys.controller.result.FormResult;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.ui.ext.ExtTemplate;
import com.wl.dzt.sys.util.DynaBean;
import com.wl.dzt.sys.util.WebUtils;
import com.wl.dzt.sys.util.clazz.ClassUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/10/010
 * @description 用于图片上传，和前台图片上传插件相对应
 */
@ApiIgnore
@Controller
@RequestMapping("admin/img")
public class ImgFileuploadController {
    public static final Logger log = LoggerFactory.getLogger(ImgFileuploadController.class);

    /**
     * <b>图片显示</b>
     * <p>
     * 根据所属类<br>
     * 数据ID<br>
     * 图片字段<br>
     * 获取一个图片
     * </p>
     *
     * @param token
     * @param response
     * @param clazz
     * @param id
     * @param field
     */
    @RequestMapping("show")
    public void img(HttpServletResponse response, String clazz, String id, String field, String token) {
        Object obj = DB.get(ClassUtil.createClass(clazz), id, field);
        if (obj == null)
            return;
        BeanMap beanMap = BeanMap.create(obj);
        String img = beanMap.get(field) + "";
        try {
            byte[] b = new BASE64Decoder().decodeBuffer(img);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            response.getOutputStream().write(b);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <b>图片上传</b>
     * <p>
     * 将所有的图片流转换成base64<br>
     * 并且将图片质量压缩<br>
     * 最终成为字符串填充到参数中
     * </p>
     *
     * @param response
     * @param request
     * @param file
     */
    @RequestMapping("uploadImg")
    public void uploadImg(HttpServletResponse response, HttpServletRequest request,
                          @RequestParam(required = false) MultipartFile file) {
        Double size = file.getSize() / 1024D / 1024D;
        User user = WebUtils.getUser(request);
        Double imgFieldSzie = (Double) user.getConfig().get("IMG_FILE_SIZE");
        if (size > imgFieldSzie) {
            FormResult formResult = new FormResult();
            formResult.setField("file");
            formResult.setSuccess(false);
            Map<String, String> map = new HashMap<>();
            map.put("file", "文件过大");
            formResult.setErrors(map);
            ExtTemplate.formTemplate(formResult, response);
        } else {
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                //图片压缩
                BufferedImage bufferedImage = zoomImage(file.getInputStream());
                ImageIO.write(bufferedImage, "jpg", os);
                //上传阿里云
                String returnUrl = OSSFactory.build().uploadSuffix(os.toByteArray(), file.getOriginalFilename());
                log.debug("阿里云图片上传返回路径为{}", returnUrl);
                WebUtils.json(new DynaBean().set("success", true).set("imgStr", returnUrl).getMap(), response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * <b>图片质量压缩</b>
     * <p>
     * 按照一定质量压缩图片
     * </p>
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public BufferedImage zoomImage(InputStream inputStream) throws IOException {
        BufferedImage result;
        BufferedImage im = ImageIO.read(inputStream);
        /* 原始图像的宽度和高度 */
        int width = im.getWidth();
        int height = im.getHeight();
        // 压缩计算
        float resizeTimes = 0.8f; /* 这个参数是要转化成的倍数,如果是1就是转化成1倍 */
        /* 调整后的图片的宽度和高度 */
        int toWidth = (int) (width * resizeTimes);
        int toHeight = (int) (height * resizeTimes);
        /* 新生成结果图片 */
        result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
        result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        return result;
    }
}
